<template>
  <el-dialog :title="title" :visible="dialogVisible" :before-close="handleClose">
    <el-form
      :model="form"
      :rules="rules"
      ref="form"
      label-position="left"
      label-width="100px"
      label-suffix=":"
      class="form"
    >
      <el-form-item label="通知内容" prop="content">
        <el-input type="textarea" v-model="form.content" :rows="4" placeholder="请输入通知内容"></el-input>
      </el-form-item>
      <el-form-item label="发送时间" prop="send_time">
        <el-date-picker
          v-model="form.send_time"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          placeholder="请选择日期时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="播放时长" prop="duration">
        <el-input v-model="form.duration" placeholder="请输入播放时长">
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer">
      <el-button @click="handleClose">返回</el-button>
      <el-button type="primary" @click="submitForm('form')">立即创建</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { messageAddApi, messageUpdateApi } from "@/api/modules/message"
export default {
  props: {
    isShow: Boolean,
    row: Object
  },
  data() {
    return {
      title: "添加通知",
      dialogVisible: false,
      form: {
        content: "",
        send_time: undefined,
        duration: ""
      },
      rules: {
        content: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
        send_time: [{ required: true, message: "请选择日期时间", trigger: "blur" }],
        duration: [
          { required: true, message: "请输入播放时长", trigger: "blur" },
          { required: true, pattern: new RegExp(/^[1-9]\d*$/, "g"), message: "请输入数字" }
        ]
      }
    }
  },
  watch: {
    isShow(val) {
      this.dialogVisible = val
    },
    row(val) {
      for (const key in val) {
        this.form[key] = val[key]
      }
    }
  },
  created() {},
  methods: {
    handleClose() {
      this.resetForm("form")
      this.$emit("close")
    },
    submit() {
      if (this.row.id) {
        messageUpdateApi({ ...this.form }).then(res => {
          this.resetForm("form")
          this.$emit("update")
          this.$emit("close")
        })
      } else {
        messageAddApi({ ...this.form }).then(res => {
          this.resetForm("form")
          this.$emit("update")
          this.$emit("close")
        })
      }
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) this.submit()
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    }
  }
}
</script>

<style lang="less" scoped>
.el-date-editor.el-input,
.el-date-editor.el-input__inner {
  width: 100%;
}
</style>
